package org.chen.wx.controller;

import org.chen.api.utils.JsonUtil;
import org.chen.wx.dto.AccessToken;
import org.chen.wx.dto.WxUserInfo;
import org.chen.wx.utils.WxUserInfoUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

/**
 * Author:Mr.Chen
 * Date:2018/8/3
 */
@RestController
@RequestMapping(value = "wx")
public class WxUserInfoController {

    @Value("${wx.host}")
    private String host;

    @Value("${wx.appid}")
    private String appid;

    @Resource
    private WxUserInfoUtils wxUserInfoUtils;

    @RequestMapping(value = "basetoken")
    public void getBaseAccessToken() {
        wxUserInfoUtils.getBaseAccessToken();
    }

    @RequestMapping(value = "index")
    public void requestCode(HttpServletResponse response) {
        try {
            String redirect_url = URLEncoder.encode(host, "utf-8");
            String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + redirect_url + "&response_type=code" + "&scope=snsapi_base" + "&state=STATE" + "&connect_redirect=#wechat_redirect";
            response.sendRedirect(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @RequestMapping(value = "userinfo")
    public void requestAccessToken(@RequestParam String code) {
        //通过code获取openid
        AccessToken accessToken = wxUserInfoUtils.getAccessToken(code);
        //通过openid获取用户信息
        WxUserInfo wxUserInfo = wxUserInfoUtils.getUserInfo(accessToken.getOpenid());
        System.out.println(JsonUtil.toJson(wxUserInfo));
    }

}

